<template>
  <view class="content">
    <view class="select">
      <input
        @click="pickSb"
        v-model="data.showText"
        disabled
        placeholder-style="color:#B6BFC6"
        placeholder="请选择设备(非必选)"
      />
      <image
        style="width: 32rpx; height: 32rpx; margin: 30rpx 0 0 14rpx"
        v-if="data.asset_sn && !data.id"
        @click="clearSb"
        src="@/static/image/input_delete.png"
      />
      <image
        style="width: 32rpx; height: 32rpx; margin: 30rpx 0 0 14rpx"
        v-else
        @click="scan"
        src="@/static/image/scan.png"
      />
    </view>
    <picker
      v-if="!data.id"
      @change="bindPickerChange"
      :value="gzdjIndex"
      range-key="NAME"
      :range="xjgl_gzdj"
    >
      <view class="select">
        <input
          v-model="gzdjName"
          disabled
          placeholder-style="color:#B6BFC6"
          placeholder="请选择故障等级"
        />
        <image src="@/static/image/arrow_right_gray.png" />
      </view>
    </picker>
    <view v-else class="select">
      <input
        v-model="gzdjName"
        disabled
        placeholder-style="color:#B6BFC6"
        placeholder="请选择故障等级"
      />
    </view>
    <picker
      v-if="!data.id"
      @change="bindPickerChange2"
      :value="gzlxIndex"
      range-key="NAME"
      :range="xjgl_gzlx"
    >
      <view class="select">
        <input
          v-model="gzlxName"
          disabled
          placeholder-style="color:#B6BFC6"
          placeholder="请选择故障类型"
        />
        <image src="@/static/image/arrow_right_gray.png" />
      </view>
    </picker>
    <view v-else class="select">
      <input
        v-model="gzlxName"
        disabled
        placeholder-style="color:#B6BFC6"
        placeholder="请选择故障等级"
      />
    </view>
    <view class="select">
      <input
        v-model="fxsj"
        @click="$refs.TimePicker.show()"
        disabled
        placeholder-style="color:#B6BFC6"
        placeholder="请选择发现时间"
      />
      <image src="@/static/image/arrow_right_gray.png" />
    </view>
    <textarea
      :disabled="data.id"
      placeholder-style="color:#B6BFC6"
      class="textarea"
      v-model="data.gzms"
      maxlength="1000"
      placeholder="请输入故障描述"
    />
    <textarea
      :disabled="data.id"
      placeholder-style="color:#B6BFC6"
      class="textarea"
      v-model="data.bz"
      maxlength="200"
      placeholder="请输入备注"
    />

    <view class="wrap">
      <view class="item" v-for="(item, index) in data.files" :key="index">
        <image class="image" @click="previewImage(index)" :src="item" />
        <image
          v-if="filesFlag && !data.id"
          @click="fileDelete(index)"
          class="del"
          src="@/static/image/input_delete.png"
        />
      </view>
      <view
        class="item"
        v-if="!data.id"
        @click="photo"
        style="border-radius: 12rpx"
      >
        <view style="display: block">
          <image src="@/static/image/photo_upload_gray.png" />
          <view
            style="
              font-size: 24rpx;
              line-height: 28rpx;
              color: #9197ae;
              text-align: center;
              margin-top: 0;
            "
            >添加图片</view
          >
        </view>
      </view>
      <view
        class="item"
        v-if="data.files.length % 3 > 0"
        style="background: white"
        v-for="item in (data.id ? 3 : 2) - (data.files.length % 3)"
      />
    </view>
    <view
      class="foot_wrap"
      v-if="!data.id"
      :style="{ paddingBottom: ios ? 'env(safe-area-inset-bottom)' : '40rpx' }"
    >
      <view class="foot" @click="submit"> 确定 </view>
    </view>
    <uni-popup ref="popup" type="bottom">
      <view class="search">
        <input
          @input="search"
          v-model="searchValue"
          placeholder-style="color:#B6BFC6"
          placeholder="请输入名称或编码进行搜索"
      /></view>
      <scroll-view
        scroll-y
        style="height: calc(100vh - 360rpx); background: #fff"
      >
        <ly-tree
          v-if="dict.length"
          ref="tree"
          :tree-data="dict"
          :props="props"
          :defaultCheckedKeys="data.asset_id ? [data.asset_id] : []"
          node-key="id"
          showRadio
          defaultExpandAll
          :childVisibleForFilterNode="true"
          :expandOnCheckNode="false"
          checkOnClickNode
          :showNodeIcon="true"
          @check="check"
          :filterNodeMethod="filterNodeMethod"
        >
        </ly-tree>
      </scroll-view>
      <view class="popupwrap">
        <view class="popupbtn" @click="$refs.popup.close()">确定</view>
      </view>
    </uni-popup>
    <TimePicker ref="TimePicker" @submit="handleSubmit"></TimePicker>
  </view>
</template>

<script>
import API from "@/common/api.js";
import util from "@/common/util.js";
import uniPopup from "@/components/uni-popup/uni-popup.vue";
import LyTree from "@/components/ly-tree/ly-tree.vue";
import TimePicker from "@/components/datetime-picker/datetime-picker.vue";

export default {
  components: {
    LyTree,
    uniPopup,
    TimePicker,
  },
  data() {
    return {
      ios: uni.getStorageSync("ios"),
      pzhAuthorization: uni.getStorageSync("pzhAuthorization"),
      data: {
        asset_sn: "",
        asset_mc: "",
        showText: "",
        asset_id: 0,
        gzdj: "",
        gzlx: "",
        gzms: "",
        bz: "",
        files: [],
      },
      dict: [],
      searchValue: "",

      xjgl_gzdj: [],
      gzdjIndex: 0,
      gzlxIndex: 0,
      gzdjName: "",
      gzlxName: "",
      fxsj: "",
      filesFlag: true,
      props: function () {
        return {
          // 这里的label就可以使用函数进行自定义的渲染了
          label(data, node) {
            return node.data.sbmc + `(${node.data.sn})`;
          },
          icon: "ICONURL",
        };
      },
      filterNodeMethod: function (value, data) {
        if (data.sbmc.indexOf(value) > -1 || data.sn.indexOf(value) > -1) {
          return true;
        } else {
          return false;
        }
      },
    };
  },
  onLoad(options) {
    let data = JSON.parse(uni.getStorageSync("inspectFaultData"));
    if (data.gzdj) {
      this.data = data;
    } else {
      this.data.asset_id = data.asset_id;
      this.data.asset_sn = data.asset_sn;
      this.data.asset_mc = data.asset_mc;
    }
    if (this.data.asset_mc) {
      this.data.showText = this.data.asset_mc + `(${this.data.asset_sn})`;
    }
    if (this.data.gzms) {
      uni.setNavigationBarTitle({
        title: "修改故障单",
      });
    }
    if (this.data.gzdj_desc) {
      uni.setNavigationBarTitle({
        title: "故障单详情",
      });
      this.gzdjName = this.data.gzdj_desc;
      this.gzlxName = this.data.gzlx_desc;
      this.fxsj = this.data.fxsj;
    } else {
      this.selectSbTree();
      this.selectDictOptionsList();
    }
    let now = new Date(),
      e = {
        year: now.getFullYear(),
        month: now.getMonth() > 9 ? now.getMonth() : "0" + now.getMonth(),
        day: now.getDate() > 9 ? now.getDate() : "0" + now.getDate(),
        hour: now.getHours() > 9 ? now.getHours() : "0" + now.getHours(),
        minute:
          now.getMinutes() > 9 ? now.getMinutes() : "0" + now.getMinutes(),
      };
    this.handleSubmit(e);
  },
  methods: {
    handleSubmit(e) {
      this.fxsj =
        e.year + "-" + e.month + "-" + e.day + " " + e.hour + ":" + e.minute;
      this.$forceUpdate();
    },
    search() {
      this.$refs.tree.filter(this.searchValue);
    },
    submit() {
      if (!this.data.gzms) {
        uni.showToast({
          icon: "none",
          title: "请输入故障描述",
          duration: 2000,
        });
        return;
      }
      let pages = getCurrentPages(); //获取所有页面栈实例列表
      let prevPage = pages[pages.length - 2]; //上一页页面实例
      prevPage.$vm.fault = this.data;
      uni.navigateBack({
        delta: 1,
      });
    },
    photo() {
      uni.chooseImage({
        count: 100,
        sizeType: ["compressed", "original"], //可以指定是原图'original', 还是压缩图，默认二者都有
        success: (res) => {
          this.data.files = this.data.files.concat(res.tempFilePaths);
          this.$forceUpdate();
        },
        error: (e) => {
          console.log(e);
        },
      });
    },
    fileDelete(index) {
      // if(this.data.files[index].indexOf('&token')>-1){
      // 	this.ids.push(this.data.files[index].id)
      // 	this.data.files.splice(index,1)
      // }
      this.data.files.splice(index, 1);
      if (this.data.files.length == 1) {
        this.filesFlag = false;
        setTimeout(() => {
          this.filesFlag = true;
        }, 10);
      }
    },
    previewImage(index) {
      uni.previewImage({
        current: this.data.files[index], // 当前显示图片的http链接
        urls: this.data.files, // 需要预览的图片http链接列表
      });
    },
    bindPickerChange(e) {
      this.data.gzdj = this.xjgl_gzdj[e.detail.value].CODE;
      this.gzdjName = this.xjgl_gzdj[e.detail.value].NAME;
    },
    bindPickerChange2(e) {
      this.data.gzlx = this.xjgl_gzlx[e.detail.value].CODE;
      this.gzlxName = this.xjgl_gzlx[e.detail.value].NAME;
    },
    selectDictOptionsList() {
      if (uni.getStorageSync("djlxDict")) {
        let data = uni.getStorageSync("djlxDict");
        this.xjgl_gzdj = data.xjgl_gzdj;
        this.xjgl_gzlx = data.xjgl_gzlx;
        this.data.gzdj = data.xjgl_gzdj[0].CODE;
        this.data.gzlx = data.xjgl_gzlx[0].CODE;
        this.gzdjName = data.xjgl_gzdj[0].NAME;
        this.gzlxName = data.xjgl_gzlx[0].NAME;
      } else {
        API.selectDictOptionsList({
          pzhAuthorization: this.pzhAuthorization,
          params: `[{"parentId":"xjgl_gzdj","keyField":"CODE","textField":"NAME","needNull":false},
                    {"parentId":"xjgl_gzlx","keyField":"CODE","textField":"NAME","needNull":false}]`,
        }).then((res) => {
          if (res.resCode == "success") {
            uni.hideLoading();
            uni.setStorage({
              key: "djlxDict",
              data: res.datas,
            });
            this.xjgl_gzdj = res.datas.xjgl_gzdj;
            this.xjgl_gzlx = res.datas.xjgl_gzlx;
            this.data.gzdj = res.datas.xjgl_gzdj[0].CODE;
            this.data.gzlx = res.datas.xjgl_gzlx[0].CODE;
            this.gzdjName = res.datas.xjgl_gzdj[0].NAME;
            this.gzlxName = res.datas.xjgl_gzlx[0].NAME;
          }
        });
      }
    },
    selectSbTree() {
      uni.getStorage({
        key: "sbDict",
        success: (res) => {
          this.dict = res.data;
        },
        fail: () => {
          API.selectSbTree({
            non_rela: "non_rela",
            pzhAuthorization: this.pzhAuthorization,
          }).then((res) => {
            if (res.resCode == "success") {
              uni.hideLoading();
              this.dict = this.toTreeData(res.datas);
              uni.setStorage({
                key: "sbDict",
                data: this.dict,
              });
            }
          });
        },
      });
    },
    toTreeData(data) {
      let resData = data;
      let tree = [];

      for (let i = 0; i < resData.length; i++) {
        if (resData[i].parent_id == "0") {
          resData[i].children = [];
          tree.push(resData[i]);
          resData.splice(i, 1);
          i--;
        }
      }
      run(tree);
      function run(chiArr) {
        if (resData.length !== 0) {
          for (let i = 0; i < chiArr.length; i++) {
            for (let j = 0; j < resData.length; j++) {
              if (chiArr[i].id === resData[j].parent_id) {
                resData[j].children = [];
                chiArr[i].children.push(resData[j]);
                resData.splice(j, 1);
                j--;
              }
            }
            run(chiArr[i].children);
          }
        }
      }
      return tree;
    },
    pickSb() {
      if (!this.data.id) {
        uni.showLoading();
        this.searchValue = "";
        this.$refs.popup.open();
        setTimeout(() => {
          uni.hideLoading();
        }, 3000);
      }
    },
    clearSb() {
      this.data.asset_sn = "";
      this.data.asset_mc = "";
      this.data.asset_id = 0;
      this.data.showText = "";
    },
    check() {
      let list = this.$refs.tree.getCheckedNodes();
      list.forEach((item) => {
        this.data.asset_sn = item.sn;
        this.data.asset_mc = item.sbmc;
        this.data.asset_id = item.id;
        this.data.showText = this.data.asset_mc + `(${this.data.asset_sn})`;
      });
    },
    scan() {
      uni.scanCode({
        success: (res) => {
          console.log(res, "www");
          if (res.errMsg == "scanCode:ok") {
            try {
              let data = JSON.parse(res.result);
              if (data.sn) {
                API.selectSbtz({
                  pzhAuthorization: this.pzhAuthorization,
                  flag: "info",
                  canDel: 0,
                  sbbm: data.sn,
                }).then((res) => {
                  if (res.resCode == "success") {
                    uni.hideLoading();
                    if (res.datas.length) {
                      this.data.asset_sn = res.datas[0].sn;
                      this.data.asset_mc = res.datas[0].sbmc;
                      this.data.asset_id = res.datas[0].id;
                      this.data.showText =
                        this.data.asset_mc + `(${this.data.asset_sn})`;
                    } else {
                      uni.showToast({
                        title: "未查询到相关数据",
                        duration: 2000,
                        icon: "none",
                      });
                    }
                  }
                });
              } else {
                uni.showToast({
                  title: "请扫描正确的设备二维码",
                  duration: 2000,
                  icon: "none",
                });
              }
            } catch (err) {
              uni.showToast({
                title: "请扫描正确的设备二维码",
                duration: 2000,
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>
<style lang="less">
.content {
  .uni-popup__wrapper-box {
    padding: 0 !important;
    background: rgba(0, 0, 0, 0) !important;
    max-width: 100% !important;
    margin-top: -220rpx;
  }
}
scroll-view ::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
  display: none;
}
</style>
<style lang="less" scoped>
/* #ifndef APP-NVUE */
body {
  font-size: 30rpx;
  line-height: 2em;
  color: #333;
  font-family: Helvetica Neue, Helvetica, sans-serif;
}

view,
text {
  font-size: 30rpx;
  line-height: 2em;
  color: #333;
}

page {
  background: #fff;
}

button {
  width: 100%;
}
/* #endif */
.content {
  background: white;
  padding: 0rpx 32rpx 260rpx 32rpx;
  font-size: 28rpx;
  width: calc(100vw - 64rpx);
  min-height: calc(100vh - 232rpx);
  .select {
    display: flex;
    margin-top: 20rpx;
    border-bottom: 1px solid #eef1f1;
    image {
      width: 20rpx;
      height: 40rpx;
      display: block;
      margin: 20rpx 0 0 20rpx;
    }
    .address {
      width: calc(100% - 104rpx);
      padding-top: 10rpx;
      font-size: 26rpx;
      margin: 0 20rpx;
    }
    input {
      width: calc(100% - 104rpx);
      padding: 20rpx 0;
      font-size: 30rpx;
      margin: 0 20rpx;
    }

    text {
      width: 222rpx;
      font-size: 30rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(143, 188, 197, 1);
      line-height: 124rpx;
      margin-left: 20rpx;
      text-align: right;
    }
  }
  .popupwrap {
    border-top: 2rpx solid rgba(149, 149, 149, 0.1);
    background: white;
    padding: 60rpx 20vw;
    .popupbtn {
      width: 60vw;
      line-height: 80rpx;
      background: #01b7fc;
      color: white;
      text-align: center;
      border-radius: 40rpx;
    }
  }

  textarea {
    background: #f5f6f9;
    border-radius: 22rpx;
    width: calc(100% - 40rpx);
    padding: 20rpx;
    margin-top: 32rpx;
    height: 160rpx;
  }
  .wrap {
    margin-top: 32rpx;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .title {
      width: 100%;
      margin-bottom: 16rpx;
    }
    .item {
      margin-bottom: 32rpx;
      width: 196rpx;
      height: 136rpx;
      margin-right: 18rpx;
      background: #f5f6f9;
      .image {
        width: 100%;
        height: 100%;
        border-radius: 12rpx;
        display: block;
      }
      .del {
        width: 36rpx;
        height: 36rpx;
        right: -178rpx;
        top: -154rpx;
      }
      view {
        image {
          width: 48rpx;
          height: 48rpx;
          margin: 24rpx 0 0rpx calc(50% - 24rpx);
        }
      }
    }
  }
  .foot_wrap {
    position: fixed;
    bottom: 0;
    width: calc(100vw - 32rpx);
    margin-left: -32rpx;
    background: white;
    padding: 40rpx 0 40rpx 32rpx;
    box-shadow: 0rpx -10rpx 32rpx 0rpx rgba(0, 0, 0, 0.06);
    .foot {
      width: calc(100vw - 64rpx);
      background: rgba(74, 125, 221, 1);
      margin-top: 24rpx;
      line-height: 76rpx;
      text-align: center;
      color: white;
      border-radius: 8rpx;
    }
  }
  .search {
    background: #ffffff;
    padding-top: 20rpx;
    input {
      width: 70vw;
      margin-left: 15vw;
      padding: 0 40rpx;
      box-sizing: border-box;
      border: 1rpx solid #ebedf0;
      border-radius: 40rpx;
      line-height: 60rpx;
      height: 60rpx;
    }
  }
}
</style>
